package org.activemonitoring.datastore.jms;

import java.io.StringReader;
import java.io.StringWriter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.activemonitoring.domain.Measures;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

public class MeasuresXmlConverter implements MessageConverter {

    private JAXBContext context;

    public MeasuresXmlConverter() throws JAXBException {
        super();
        this.context = createJaxbContext();
    }

    protected JAXBContext createJaxbContext() throws JAXBException {
        return JAXBContext.newInstance(Measures.class);
    }

    @Override
    public Object fromMessage(Message message) throws JMSException, MessageConversionException {
        Validate.isTrue(message instanceof TextMessage, "This converter supports only JMS TextMessage");
        TextMessage textMessage = (TextMessage) message;
        try {
            Unmarshaller unmarshaller = this.context.createUnmarshaller();
            return unmarshaller.unmarshal(new StringReader(textMessage.getText()));
        } catch (JAXBException e) {
            Throwable t = ExceptionUtils.getRootCause(e);
            throw new MessageConversionException("Can't convert jms message content", t);
        }
    }

    @Override
    public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
        Validate.isTrue(object instanceof Measures, "This converter supports only Measures objects");
        StringWriter writer = new StringWriter();
        try {
            Marshaller marshaller = this.context.createMarshaller();
            marshaller.marshal(object, writer);
        } catch (JAXBException e) {
            Throwable t = ExceptionUtils.getRootCause(e);
            throw new MessageConversionException("Can't convert object to jms text message", t);
        }
        return session.createTextMessage(writer.toString());
    }
}
